package com.tjcd.project.library_base.common.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.provider.MediaStore;


import com.tjcd.project.library_base.BaseApplication;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @Author jiangKunKun
 * @CreateDate 2021/7/12
 * @Description 下载文件
 * @SpittingGrooves
 */
public class DownloadUtil {
    private static DownloadUtil downloadUtil;
    /**
     * 网络连接
     */
    private final OkHttpClient okHttpClient;

    /**
     * 单例
     * @return
     */
    public static DownloadUtil get() {
        if (downloadUtil == null) {
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    private DownloadUtil() {
        okHttpClient = new OkHttpClient();
    }

    /** 保存文件
     * @param url          下载连接
     * @param destFileDir  下载的文件储存目录
     * @param destFileName 下载文件名称 需要跟后缀  xxx.txt
     * @param listener     下载监听
     */
    public void download(final String url, final String destFileDir, final String destFileName, final OnDownloadListener listener) {
        Request request = new Request.Builder().url(url).build();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 下载失败监听回调
                listener.onDownloadFailed(e);
            }

            @Override
            public void onResponse(Call call, Response response) {
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                File dir = new File(destFileDir);
                if (!dir.exists()) {
                    dir.mkdirs();
                }
                File file = new File(dir, destFileName);
                // 解决安卓10相册显示问题
                ContentResolver localContentResolver = BaseApplication.mContext.getContentResolver();
                ContentValues localContentValues = getVideoContentValues(file, System.currentTimeMillis());
                localContentResolver.insert(MediaStore.Video.Media.EXTERNAL_CONTENT_URI, localContentValues);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中更新进度条
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess(file);
                } catch (Exception e) {
                    listener.onDownloadFailed(e);
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                    }
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                    }
                }
            }
        });
    }

    /**
     * 安卓10 相册显示问题
     * @param paramFile
     * @param paramLong
     * @return
     */
    private static ContentValues getVideoContentValues(File paramFile, long paramLong){
        ContentValues localContentValues = new ContentValues();
        localContentValues.put("title", paramFile.getName());
        localContentValues.put("_display_name", paramFile.getName());
        localContentValues.put("mime_type", "video/3gp");
        localContentValues.put("datetaken", Long.valueOf(paramLong));
        localContentValues.put("date_modified", Long.valueOf(paramLong));
        localContentValues.put("date_added", Long.valueOf(paramLong));
        localContentValues.put("_data", paramFile.getAbsolutePath());
        localContentValues.put("_size", Long.valueOf(paramFile.length()));
        return localContentValues;
    }

    public interface OnDownloadListener {
        /**
         * @param file 下载成功后的文件
         */
        void onDownloadSuccess(File file);

        /**
         * @param progress 下载进度
         */
        void onDownloading(int progress);

        /**
         * @param e 下载异常信息
         */
        void onDownloadFailed(Exception e);
    }

    /**
     * 本地bitmap保存图片
     * @param destFileDir 下载的文件储存目录
     * @param destFileName 图片名称包含后缀
     * @param bitmap 图片
     * @return
     */
    public static String saveBitmapGallery(final String destFileDir, final String destFileName, Bitmap bitmap) {
        OutputStream out = null;
        String[] pathArray = null;
        String[] typeArray = null;
        try {
            // Android 10版本 创建文件夹不成功，这里没有过多去研究
            File mPicFile = new File(destFileDir, destFileName);
            String mPicPath = mPicFile.getAbsolutePath();
            pathArray = new String[]{mPicFile.getAbsolutePath()};
            typeArray = new String[]{"image/jpeg"};
            ContentValues values = new ContentValues();
            ContentResolver resolver = BaseApplication.getInstance().getContentResolver();
            values.put(MediaStore.Images.ImageColumns.DATA, mPicPath);
            values.put(MediaStore.Images.ImageColumns.DISPLAY_NAME, destFileName);
            values.put(MediaStore.Images.ImageColumns.MIME_TYPE, "image/jpeg");
            values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, System.currentTimeMillis() + "");
            // 插入相册
            Uri uri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            if (uri != null) {
                out = resolver.openOutputStream(uri);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
            }
            return mPicFile.getPath();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.flush();
                    out.close();
                    // 扫描刷新
                    MediaScannerConnection.scanFile(BaseApplication.getInstance(), pathArray, typeArray, (s, uri) -> {
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

}
